package cn.shyouchi.wuguanjia.android.ui.event.meet;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.event.rank.EventRankEntity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.dialog.TimePickerDialogFragment;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

@RuntimePermissions
public class AddMeetActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_arrange_mode)
    TextView mTvArrangeMode;
    @BindView(R.id.item_sel_order)
    LinearLayout mItemSelOrder;
    @BindView(R.id.tv_meet_time)
    TextView mTvMeetTime;
    @BindView(R.id.tv_meet_address)
    EditText mTvMeetAddress;
    @BindView(R.id.edit_meet_content)
    EditText mEditMeetContent;
    @BindView(R.id.photo_snpl)
    BGASortableNinePhotoLayout mPhotoSnpl;
    @BindView(R.id.activity_add_handover)
    LinearLayout mActivityAddHandover;

    EventApi mEventApi;
    String projectId;
    String startTime;

    List<EventRankEntity.ResultMessageBean> mRankEntityList = new ArrayList<>();

    List<String> mRankList = new ArrayList<>();
    EventRankEntity.ResultMessageBean rankEntity;

    ArrayList<String> photos = new ArrayList<>();


    EventMeetEntity.ResultMessageBean entity;

    boolean isEdit = false;

    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;


    @Override
    public int initContentView() {
        return R.layout.activity_add_meet;
    }

    @Override
    public void initInjector() {
        mEventApi = new EventApi(mContext);
        projectId = getIntent().getStringExtra("projectId");
        entity = getIntent().getParcelableExtra("meet");
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());

        mPhotoSnpl.init(this);
        mPhotoSnpl.setDelegate(this);

        mEventApi.getRankList(projectId)
                .subscribeOn(Schedulers.io())
                .map(new Func1<EventRankEntity, List<EventRankEntity.ResultMessageBean>>() {
                    @Override
                    public List<EventRankEntity.ResultMessageBean> call(EventRankEntity entity) {
                        mRankList.clear();
                        for (EventRankEntity.ResultMessageBean bean : entity.getResultMessage()) {
                            mRankList.add(bean.getServicesname());
                        }
                        return entity.getResultMessage();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<List<EventRankEntity.ResultMessageBean>>(mContext) {
                    @Override
                    public void onNext(List<EventRankEntity.ResultMessageBean> resultMessageBeanList) {
                        mRankEntityList.addAll(resultMessageBeanList);
                    }
                });


        if (entity != null) {
            isEdit = true;
            initEntity();
            ToastUtil.showToast("编辑状态");
        }

    }

    private void initEntity() {

        mTvArrangeMode.setText(entity.getService().getServicesname());
        mTvMeetTime.setText(entity.getMeetingtime());
        mTvMeetAddress.setText(entity.getMeetingplace());
        mEditMeetContent.setText(entity.getMeetingcontent());
        mPhotoSnpl.setData((ArrayList<String>) entity.getImage());

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("保存");
        menuItem.setShowAsAction(2);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("保存")) {
            generateEntityExit();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void generateEntityExit() {

        if (rankEntity == null) {
            ToastUtil.showToast("请选择班次");
            return;
        }

        if (TextUtils.isEmpty(startTime)) {
            ToastUtil.showToast("请选择开始时间");
            return;
        }
//        if (TextUtils.isEmpty(mEditMeetContent.getText())) {
//            mEditMeetContent.setError("");
//            return;
//        }
        if (TextUtils.isEmpty(mTvMeetAddress.getText())) {
            mTvMeetAddress.setError("地址不能为空");
            return;
        }



        mEventApi.addMeet(projectId,
                String.valueOf(rankEntity.getId()),
                mTvMeetAddress.getText().toString(),
                startTime, mEditMeetContent.getText().toString(),
                mPhotoSnpl.getData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult result) {
                        setResult(EventMeetActivity.REQUEST_TYPE_ADD_SUCCESS);
                        finish();
                    }
                });

    }

    @OnClick({R.id.item_sel_order, R.id.tv_meet_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.item_sel_order:
                showSelDia();
                break;
            case R.id.tv_meet_time:
                showTimePicker(mTvMeetTime, "开始时间");
                break;
        }
    }

    private synchronized void showSelDia() {
        String[] ranks = mRankList.toArray(new String[mRankList.size()]);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("选择班次");
        builder.setCustomTitle(tvTitle);
        builder.setItems(mRankList.toArray(ranks), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                onModeChange(mRankEntityList.get(which));
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    private void onModeChange(EventRankEntity.ResultMessageBean resultMessageBean) {
        rankEntity = resultMessageBean;
        mTvArrangeMode.setTextColor(getResources().getColor(R.color.mainColor));
        mTvArrangeMode.setText(resultMessageBean.getServicesname());
    }

    public void showTimePicker(final TextView tv, String title) {
        TimePickerDialogFragment mTimePickerDialog;
        mTimePickerDialog = new TimePickerDialogFragment(getSupportFragmentManager(), title, "");
        mTimePickerDialog.setOnTimePickedListener(new TimePickerDialogFragment.onTimePickedListener() {
            @Override
            public void onPicked(String time) {
                tv.setText(time);
                startTime = time;
            }
        });
        mTimePickerDialog.showDialog();
    }


    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        AddMeetActivityPermissionsDispatcher.choicePhotoWrapperWithCheck(this);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotoSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, mPhotoSnpl.getMaxItemCount(), models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);

    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void choicePhotoWrapper() {
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "TakePhoto");
        startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 3, null, true), REQUEST_CODE_CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            photos.addAll(BGAPhotoPickerActivity.getSelectedImages(data));
            mPhotoSnpl.setData(photos);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            mPhotoSnpl.setData(BGAPhotoPickerActivity.getSelectedImages(data));
        }
    }
}
